<template>
  <el-card class="box-card">
    <div slot="header" class="clearfix">
      <span>重置密码</span>
    </div>
    <div>
      <!-- 列表内容 -->
      <el-form ref="form" label-width="120px" :model="pass" :rules="rules">
        <el-form-item label="原密码" prop="old_pwd">
          <el-input v-model="pass.old_pwd"></el-input>
        </el-form-item>
        <el-form-item label="新密码" prop="new_pwd">
          <el-input v-model="pass.new_pwd"></el-input>
        </el-form-item>
        <el-form-item label="确认新密码" prop="re_pwd">
          <el-input v-model="pass.re_pwd"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="updatepwd">确认修改</el-button>
          <el-button>取消</el-button>
        </el-form-item>
      </el-form>
    </div>
  </el-card>
</template>

<script>
import { updatepwdAPI } from '@/api/user'
export default {
  data() {
    const newpwd = (rule, value, callback) => {
      if (value === this.pass.old_pwd) {
        callback(new Error('新密码和原密码不能相同'))
      } else {
        callback()
      }
    }
    const repwd = (rule, value, callback) => {
      if (value === this.pass.new_pwd) {
        callback()
      } else {
        callback(new Error('两次密码不一致'))
      }
    }
    return {
      pass: {
        old_pwd: '',
        new_pwd: '',
        re_pwd: ''
      },
      rules: {
        old_pwd: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 6, max: 15, message: '长度在 6 到 15 个字符', trigger: 'blur' }
        ],
        new_pwd: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 6, max: 15, message: '长度在 6 到 15 个字符', trigger: 'blur' },
          { validator: newpwd, trigger: 'blur' }
        ],
        re_pwd: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 6, max: 15, message: '长度在 6 到 15 个字符', trigger: 'blur' },
          { validator: repwd, trigger: 'blur' }
        ]
      }
    }
  },
  methods: {
    updatepwd() {
      this.$refs.form.validate(async valid => {
        if (!valid) return
        const { data: res } = await updatepwdAPI(this.pass)
        if (res.code === 0) {
          this.$message.success(res.message)
          // this.$refs.form.resetFields() // 重置表单
          // -------------------- 业务逻辑场景二：重置了密码，退出，重新登录 ------------------------
          // 重置vuex中的 token、user，然后跳转到登录 （和退出一样）
          this.$store.commit('user/updataToKen', '') // 清空token
          this.$store.commit('user/updataUser', {}) // 清空user用户信息
          this.$router.push('/login')
        } else {
          this.$message.error(res.message)
        }
      })
    }
  }
}
</script>

<style lang="less" scoped>
.el-card {
  font-size: 13px;
}

.el-form {
  width: 500px;
}
</style>
